import { sleep } from "@/utils";
import IpcParams from "../IpcParams";
import { createAgent } from './utils';
import Axios from 'axios';
import axiosRetry from 'axios-retry';

export default class CatsGame {
  constructor(tokenInfo) {
    this.tokenInfo = tokenInfo
    const agent = createAgent(this.tokenInfo.proxy)
    const headers = {
      "Referer": "https://cats-frontend.tgapps.store/",
      "Content-Type": "application/json",
      "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_7_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
    }
    this.axios = Axios.create({
      headers: headers,
      httpAgent: agent,
      httpsAgent: agent,
      timeout: 90 * 1000,
    })
    axiosRetry(this.axios, {
      retries: 5, retryDelay: (retryCount) => {
        return 2000
      }
    });
  }

  async run() {
    try {
      let webSessionUrl = this.tokenInfo.tgweb
      if (webSessionUrl.startsWith("https://") == false) {
        console.error(`${this.gameInfo.phone}  error session url ${webSessionUrl}`);
        return
      }
      webSessionUrl = decodeURIComponent(webSessionUrl)
      let session = webSessionUrl.split("#tgWebAppData=")[1]
      session = session.split("&tgWebAppVersion")[0]
      const headers = {
        authorization: "tma " + session,
      }
      const inviteUrl = this.tokenInfo.inviteUrl
      let refId = 0
      if (inviteUrl != null) {
        refId = inviteUrl.split("startapp=")[1]
        refId = parseInt(refId)
      }
      // 注册
      try {
        const createRes = await this.axios.request("https://api.catshouse.club/user/create", {
          method: "post",
          headers,
          data: {}
        })
        this.user = createRes.data
      } catch (error) {
        console.error(error.response)
      }

      // 登录
      let userRes = await this.axios.request("https://api.catshouse.club/user", {
        methed: "get",
        headers: headers,
      })
      this.user = userRes.data
      // 任务
      const taskRes = await this.axios.request("https://api.catshouse.club/tasks/user?group=cats", {
        methed: "get",
        headers,
      })
      const taskList = taskRes.data.tasks
      for (let index = 0; index < taskList.length; index++) {
        const task = taskList[index];
        if (task.allowCheck != true && task.completed != true) {
          const url = `https://api.catshouse.club/tasks/${task.id}/complete`
          try {
            const resultRes = await this.axios.request(url, {
              method: "post",
              headers,
              data: {}
            })
            console.log(this.tokenInfo.phone, "complete task", task.id)
          } catch (error) {
            console.error(this.tokenInfo.phone, "task", url, error)
          }
          await sleep(1500)
        } else {
          // 需要check的任务
        }
      }

      // 刷新user
      userRes = await this.axios.request("https://api.catshouse.club/user", {
        methed: "get",
        headers: headers,
      })
      console.log(userRes.data)
      this.user = userRes.data

      this.tokenInfo.score = this.user.totalRewards
      const date = (new Date()).toLocaleString()
      this.tokenInfo.gameupdate = date
      this.tokenInfo.count = (this.tokenInfo.count || 0) + 1
      console.log(date, "cats end", this.tokenInfo.phone, "score: ", this.tokenInfo.score)
      return new IpcParams("runCats", this.tokenInfo)
    } catch (error) {
      console.log((new Date()).toLocaleString(), "cats error", this.tokenInfo.phone)
      if (error.response) {
        console.error(error.request.path, error.response)
      } else {
        console.error(error)
      }
      return new IpcParams("runCats", this.tokenInfo, error)
    }
  }
}
